<template>
  <div class="box">
    <div class="main">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="state.username"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, pattern, message: '请填写用户名' }]"
          />
          <van-field
            v-model="state.password"
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, pattern, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div class="help">
          <span @click="forget">忘记密码</span>
          <span @click="safecode">注册账号</span>
        </div>
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { reactive } from "vue";
import { login } from "../api";
import {useRouter} from 'vue-router'
export default {
  setup() {
    const router = useRouter()
    const state = reactive({
      username: "",
      password: "",
    });
    const onSubmit = async (values) => {
      const res = await login(values);
      console.log(res)
      if (res.errno == 0) {
        const userId = res.data.userId;
        localStorage.setItem("userId", userId);
        router.push('/recommend')
      } else {
        console.log(res.message);
      }
    };
    const forget = () => {
      router.push('/forget')
    };
    const safecode = () => {
      router.push('/safecode')
    };
    const pattern = /^\d{6,12}$/;
    return {
      state,
      onSubmit,
      pattern,
      forget,
      safecode,
    };
  },
};
</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
  margin-top: 55%;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.main {
  padding: 10px;
}
.help {
  margin-left: 55%;
  font-size: 13px;
  color: #909399;
}
.help span {
  margin: 5px 8px 5px;
}
</style>